import java.io.*;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;
import java.net.URL;
import java.util.LinkedHashMap;
import java.util.Map;

public class MyHttpPost {
    private String host;
    private int port;
    private String contextPath;
    private Map<String, String> headers = new LinkedHashMap<>();
    private String fileLength;
    private StringBuilder textData = new StringBuilder();


    public MyHttpPost(String address) {
        try {
            URL url = new URL(address);
            this.host = url.getHost();
            this.port = url.getPort();
            this.contextPath = url.getPath();
            headers.put("Host", this.host);

            textData.append("------WebKitFormBoundaryoRrxWK0dShup7xlB");
            textData.append("\r\n");
            textData.append("Content-Disposition: ")
                    .append("form-data; name=\"file1\"; filename=\"a.txt\"");
            textData.append("\r\n");
            textData.append("Content-Type: text/plain");
            textData.append("\r\n");
            textData.append("\r\n");
            String fileContext = "";
            // 要上传的文件
            File file = new File("D:/a.txt");
            // 读取文件内容
            BufferedReader reader = new BufferedReader(new FileReader(file));
            String tempString = "";
            while ((tempString = reader.readLine()) != null) {
                fileContext += tempString;
            }
            textData.append(fileContext);
            textData.append("\r\n");
            textData.append("------WebKitFormBoundaryoRrxWK0dShup7xlB--");
            textData.append("\r\n");
            // 要请求到服务器的body 长度
            fileLength = String.valueOf(textData.toString().getBytes().length);
            System.out.println("fileLength===========" + textData.toString().getBytes().length);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        MyHttpPost myHttpPost = new MyHttpPost("http://localhost:8080/servlet/UploadHandleServlet");
        myHttpPost.addHeader("Connection", "keep-alive")
                .addHeader("Cache-Control", "max-age=0")
                .addHeader("Upgrade-Insecure-Requests", "1")
                .addHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.99 Safari/537.36")
                .addHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8")
                .addHeader("Accept-Encoding", "gzip, deflate, sdch")
                .addHeader("Accept-Language", "en-US,en;q=0.8,zh-CN;q=0.6,zh;q=0.4")
                .addHeader("Content-Length", myHttpPost.fileLength)
                .addHeader("Content-Type", "multipart/form-data; boundary=----WebKitFormBoundaryoRrxWK0dShup7xlB");

        try {
            InputStream inputStream  = myHttpPost.execute();
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
            String line;
            while ((line = bufferedReader.readLine()) != null) {
                System.out.print(line + "\r\n响应===============================");
            }
            inputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public InputStream execute() {
        try {
            // http 协议内容
            StringBuilder requestMessage = new StringBuilder();
            requestMessage.append("POST " + this.contextPath + " HTTP/1.1" + System.getProperty("line.separator"));
            for (String key : headers.keySet()) {
                requestMessage.append(key + ": " + headers.get(key));
                requestMessage.append("\r\n");
            }
            requestMessage.append("\r\n");
            // 请求服务器body 体
            requestMessage.append(textData);

            Socket socket = new Socket();
            SocketAddress socketAddress = new InetSocketAddress(this.host, this.port);
            socket.connect(socketAddress);
            BufferedWriter bufferedWriter = null;
            bufferedWriter = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
            System.out.println("request=================" + requestMessage.toString());
            bufferedWriter.write(requestMessage.toString());
            bufferedWriter.flush();
            return socket.getInputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    public MyHttpPost addHeader(String key, String value) {
        headers.put(key, value);
        return this;
    }

}
